package demo.ioc.my.core.ctx;

import demo.ioc.my.core.web.RequestMappingInfo;
import demo.ioc.my.core.annotation.RequestMapping;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 张少昆 on 2018/3/18.
 */
public class WebApplicationContext extends AbstractApplicationContext {
    public static final Map<String, RequestMappingInfo> URL_REQUESTMAPPING_MAP = new HashMap<>();

    public WebApplicationContext(){
        init();
    }

    //TODO 这里耦合了DefaultApplicationContext和WebApplicationContext！
    //不过仅作示意，所以取巧了。即，这里仅考虑@RequestMapping！不考虑@Controller
    @Override
    void init(){
        //扫描@RequestMapping
        CLASS_LIST.forEach(e -> {
            RequestMapping requestMapping = e.getAnnotation(RequestMapping.class);
            String t_url = requestMapping.value();

            Method[] methods = e.getMethods();
            for(Method method : methods){
                if(method.isAnnotationPresent(RequestMapping.class)){
                    RequestMapping annotation = method.getAnnotation(RequestMapping.class);

                    String m_url = annotation.value();
                    String url = joinPath(t_url, m_url);

                    RequestMappingInfo info = new RequestMappingInfo();
                    info.setClzz(e);
                    info.setInstance(CLASS_INSTANCE_MAP.get(e));
                    info.setMethod(method);
                    info.setUrl(url);

                    info.setMethod(method);

                    URL_REQUESTMAPPING_MAP.put(url, info);
                }
            }
        });
        // CLASS_INSTANCE_MAP.
    }

    /**
     * @param t_url 类上的请求路径
     * @param m_url 方法上的请求路径
     * @return
     */
    public String joinPath(String t_url, String m_url){
        if(t_url == null && m_url == null || t_url.trim().isEmpty() || m_url.trim().isEmpty()){
            throw new RuntimeException("请求路径不能为空！");
        }
        String url = '/' + t_url + '/' + m_url;
        return url.replaceAll("/+", "/");
    }
}
